package com.shg.service.search.impl;

import java.util.ArrayList;
import java.util.List;

import org.compass.core.CompassCallback;
import org.compass.core.CompassException;
import org.compass.core.CompassHits;
import org.compass.core.CompassQueryBuilder;
import org.compass.core.CompassSession;
import org.compass.core.CompassQuery.SortDirection;
import org.compass.core.CompassQuery.SortPropertyType;

import com.shg.bean.Book;
import com.shg.bean.QueryResult;

public class QueryCallBack implements CompassCallback<QueryResult<Book>> {

	//查询的类型
	private Integer type;
	//查询的关键字
	private String keyWord;
	//查询的起始位置
	private int firstResult;
	//查询的介绍位置
	private int maxResult;
	
	public QueryCallBack(Integer type, String keyWord, int firstResult,int maxResult){
		this.type=type;
		this.keyWord=keyWord;
		this.firstResult=firstResult;
		this.maxResult=maxResult;
	}
	public QueryResult<Book> doInCompass(CompassSession session)throws CompassException {
		CompassHits hits=null;
		//高级查询
		CompassQueryBuilder queryBuilder=session.queryBuilder();
		if(type==-1){//低级查询
			hits = session.find(keyWord);
		}else if(type==0){//免费
			//sql: type=1 and xxx like keyWord
			hits = queryBuilder.bool()
					.addMust(queryBuilder.spanEq("type", 0))
					.addMust(queryBuilder.queryString(keyWord).toQuery())
					.toQuery()
					.hits();
		}else if(type==1){//收费
			//sql: type=1 and xxx like keyWord order by price desc
			hits = queryBuilder.bool()
					.addMust(queryBuilder.spanEq("type", 1))
					.addMust(queryBuilder.queryString(keyWord).toQuery())
					.toQuery().addSort("price",SortPropertyType.FLOAT,SortDirection.REVERSE)
					.hits();
		}
		
		QueryResult<Book> result=new QueryResult<Book>();
		List<Book> list=new ArrayList<Book>();
		//满足条件的总记录数
		result.setResultCount(hits.length());
		//查询的起始位置+每页显示的最大记录数=查询的结束位置
		int length=firstResult+maxResult;
		//如果查询的结束位置查处大于总记录数，就设置总记录数为结束位置
		length=length>hits.length()?hits.length():length;
		for(int i=firstResult;i<length;i++){
			Book book = (Book) hits.data(i);
			//设置高亮显示的书籍名称
			if(hits.highlighter(i).fragment("bookName")!=null)
				book.setBookName(hits.highlighter(i).fragment("bookName"));
			//设置高亮显示的书籍描述
			if(hits.highlighter(i).fragment("description")!=null)
				book.setDescription(hits.highlighter(i).fragment("description"));
			list.add(book);
		}
		result.setResultList(list);
		return result;
	}

}
